package my.test.csdn.weixin_43767015.basic.ch12.transaction.declarative.annotation.propagation.nested.base.service;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Component
public class TxNestedService {
    /**
     * jdbc模版，用于操作数据库
     */
    @Resource
    private JdbcTemplate jdbcTemplate;

    /** 单独调用m2 */
	@Transactional(propagation = Propagation.NESTED)
    public void m2() {
        String sql = "insert into tx_study (name,age) values (?,?)";
        jdbcTemplate.update(sql, "TxNested", 30);
        //抛出一个RuntimeException
        throw new RuntimeException();
	}
	
	/** 相当于开启一个事务 */
    @Resource
    private DataSourceTransactionManager transactionManager;
	
    public DataSourceTransactionManager getTransactionManager() {
    	return transactionManager;
    }
	
    public void tran() {
        //获得一个事务管理器
        DataSourceTransactionManager txManager = getTransactionManager();
    	//创建一个事务定义对象，可以设置事务的属性
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        //只能以编程方式执行时才能显式设置事务名称
        def.setName("SomeTxName");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
        //m2开启一个新事务
        TransactionStatus status = txManager.getTransaction(def);
        try {
            //执行m2方法业务逻辑
            m2();
        } catch (Exception ex) {
            //回滚
            txManager.rollback(status);
            throw ex;
        }
        //提交
        txManager.commit(status);
    }

}
